package tech.senri.iot.socket.service.socket

import io.netty.buffer.ByteBuf
import io.netty.channel.ChannelHandlerContext
import io.netty.handler.codec.MessageToMessageDecoder
import java.nio.charset.Charset

class MessageDecoder : MessageToMessageDecoder<ByteBuf>()
{
    override fun decode(ctx: ChannelHandlerContext, msg: ByteBuf, out: MutableList<Any>)
    {

        /**
         * 板卡类型
         */
        val deviceType = msg.readByte().toInt()

        if (deviceType != 1) return
        /**
         * 帧类型
         */
        val messageCode = msg.readByte().toInt()
        /**
         * 帧长度
         */
        val dataLen = msg.readShort().toInt()

        val deviceId = msg.readCharSequence(15, Charset.defaultCharset()).toString()
        val funCode = if (messageCode != 0x70) msg.readUnsignedByte().toInt() else 0
        val content = if (messageCode == 0x70) msg.readBytes(dataLen - 19 - 8) else msg.readBytes(dataLen - 20 - 8)

        val datatime = ByteArray(6)

        msg.readBytes(datatime)
        Decoder.decode(Pair(messageCode, funCode), deviceId, datatime, content)?.let {
            out.add(it)
        }
    }
}
